#授权相关
from flask import Blueprint,render_template,request,jsonify,redirect,url_for,session
from flask_mail import Message
from exts import mail,db
from models import UserModel,EmailCaptchaModel
from string import digits
from random import sample
from .forms import RegisterForm,LoginForm
from werkzeug.security import generate_password_hash,check_password_hash

bp=Blueprint("auth",__name__,url_prefix='/auth')#前缀

@bp.route('/login',methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')#'登录'
    else:
        form=LoginForm(request.form)
        if form.validate():
            email=form.email.data
            password=form.password.data
            user=UserModel.query.filter_by(email=email).first()
            if not user:
                print('邮箱在数据库中不存在！')
                return redirect(url_for('auth.login'))
            if check_password_hash(user.password,password):
                #cookie只适合存储少量数据
                #flask的session是通过加密后存储在cookie中的
                session['user_id']=user.id
                return redirect('/')
            else:
                print('账号和密码不匹配！')
                return redirect('/auth/login')#url_for('auth.login')
        else:
            print(form.errors)
            return redirect('/auth/login')#url_for('auth.login')

#GET:从服务器上获取数据
#POST：从客户端的数据提交给服务器
@bp.route('/register',methods=['GET','POST'])
def register():
    if request.method=='GET':
        return render_template('register.html')
    else:
        #验证用户提交的邮箱和验证码是否对应且正确
        #表单验证：flask-wtf：wtforms
        form=RegisterForm(request.form)
        if form.validate():#自动调用自定义函数
            email=form.email.data
            username=form.username.data
            password=form.password.data
            user=UserModel(email=email,username=username,password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('auth.login'))#'/auth/login' 'success'
        else:
            print(form.errors)
            return redirect(url_for('auth.register'))#'fail'

@bp.route('/logout')
def logout():
    session.clear()
    return redirect('/')

@bp.route('/captcha/email')
def get_email_captcha():
    #/captcha/email/<email>
    #/captcha/email?email=xxx@qq.com
    email=request.args.get('email')
    source=digits*4#随机数字、字母的组合，这里扩展字符串
    captcha=sample(source,4)#随机4位
    captcha=''.join(captcha)
    print(captcha)
    #I/O：Input/Output 一般作为队列，用其他进程执行，提高速度
    message = Message(subject='邮箱验证码发送', recipients=[email], body=f'您的验证码是{captcha},请勿告知他人，五分钟内有效！')
    mail.send(message)

    #推荐用memcached或Redis存储验证码
    #这里用MySQL
    email_captcha=EmailCaptchaModel(email=email,captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()

    #可以考虑用RESTful API
    #{code：200/400/500，message：""，data：{}}
    return jsonify({"code":200,"message":"","data":None})
    #return f'验证码已发往{email}，请注意查收！'

@bp.route('/mail/test')
def mail_test():
    message=Message(subject='邮箱测试',recipients=['1459506679@qq.com'],body='这是一条测试邮件')
    mail.send(message)
    return '邮件发送成功！'